package com.demo.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.blog.common.exception.BlogException;
import com.demo.blog.common.util.JwtUtils;
import com.demo.blog.common.util.SecurityUtil;
import com.demo.blog.mapper.BlogInfoMapper;
import com.demo.blog.mapper.UserInfoMapper;
import com.demo.blog.pojo.dataobject.BlogInfo;
import com.demo.blog.pojo.dataobject.UserInfo;
import com.demo.blog.pojo.response.UserInfoParam;
import com.demo.blog.pojo.response.UserInfoResponse;
import com.demo.blog.pojo.response.UserLoginResponse;
import com.demo.blog.service.UserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BlogInfoMapper blogInfoMapper;

    @Override
    public UserLoginResponse login(UserInfoParam userInfoParam) {
        UserInfo userInfo = selectUserInfoByName(userInfoParam.getUserName());
        if (userInfo == null) {
            throw new BlogException("用户不存在");
        }
        if (!SecurityUtil.verify(userInfoParam.getPassword(), userInfo.getPassword())) {
            throw new BlogException("密码错误");
        }
        //密码正确，返回用户信息
        Map<String, Object> cliams = new HashMap<>();
        cliams.put("userId", userInfo.getId());
        cliams.put("userName", userInfo.getUserName());
        String jwt = JwtUtils.genJwt(cliams);

        return new UserLoginResponse(userInfo.getId(), jwt);
    }

    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName)
                .eq(UserInfo::getDeleteFlag, 0)
        );
    }

    @Override
    public UserInfoResponse getUserInfo(@NotNull Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse getAuthorInfo(@NotNull Integer blogId) {
        return getUserInfo(blogInfoMapper.selectById(blogId).getUserId());

    }


}
